package br.com.financas.repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.financas.abstractions.IContaRepository;
import br.com.financas.entity.Conta;
import br.com.financas.entity.Usuario;

public class ContaRepository implements IContaRepository<Conta> {
	private EntityManager manager;
	private List<Conta> contas;

	public ContaRepository(EntityManager manager) {
		this.manager = manager;
		contas = new ArrayList<Conta>();

	}

	@Override
	public void inserir(Conta conta) throws Exception {

		try {
			manager.getTransaction().begin();
			manager.persist(conta);
			manager.getTransaction().commit();
		} catch (Exception e) {
			manager.getTransaction().rollback();
			throw e;
		}
	}

	@Override
	public boolean deletar(Conta conta) {
		boolean deletado = true;
		try {
			manager.getTransaction().begin();
			manager.refresh(conta);
			manager.remove(conta);
			manager.getTransaction().commit();
		} catch (Exception e) {
			manager.getTransaction().rollback();
			deletado = false;
		}

		return deletado;

	}

	@Override
	public void atualizar(Conta conta) {
		try {
			manager.getTransaction().begin();
			manager.merge(conta);
			manager.getTransaction().commit();
		} catch (Exception e) {
			manager.getTransaction().rollback();
		}
	}

	@Override
	public List<Conta> obterTodos() {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Conta> obterPorTitulo(String titulo, Usuario usuario) {
		Query query;

		try {
			query = manager.createQuery("FROM Conta c WHERE c.titulo = :titulo AND c.usuario = :usuario");
			query.setParameter("titulo", titulo);
			query.setParameter("usuario", usuario);
			contas = query.getResultList();
		} catch (Exception e) {
			manager.getTransaction().rollback();
		}
		return contas;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Conta> obterPorUsuario(Usuario usuario) {
		Query query;

		if (this.contas.size() == 0) {
			try {
				query = manager.createQuery("SELECT c FROM Conta c WHERE c.usuario = :usuario");
				query.setParameter("usuario", usuario);
				contas = query.getResultList();
			} catch (Exception e) {
				manager.getTransaction().rollback();
			}
		}
		return contas;
	}

	@Override
	public Conta obterPorId(long id) {

		return manager.find(Conta.class, id);
	}

	@Override
	public void transferir(Conta contaOrigem, Conta contaDestino) {
		
		try {
			manager.getTransaction().begin();
			manager.merge(contaOrigem);
			manager.merge(contaDestino);
			manager.getTransaction().commit();
		
		} catch (Exception e) {
			manager.getTransaction().rollback();
		}
	}


}
